import 'package:flutter/material.dart';
import 'dart:async';
import 'package:translator_plus/translator_plus.dart';
import 'package:pool_english/services/dictionary_service.dart';

class ArticleDetailPage extends StatefulWidget {
  final int articleId;

  const ArticleDetailPage({
    Key? key,
    required this.articleId,
  }) : super(key: key);

  @override
  State<ArticleDetailPage> createState() => _ArticleDetailPageState();
}

class _ArticleDetailPageState extends State<ArticleDetailPage> {
  String? _selectedWord;
  String? _translation;
  Timer? _timer;
  final _translator = GoogleTranslator();
  bool _dictionaryReady = false;

  @override
  void initState() {
    super.initState();
    _checkDictionary();
  }

  Future<void> _checkDictionary() async {
    try {
      await DictionaryService.init();
      if (mounted) {
        setState(() {
          _dictionaryReady = true;
        });
        print('词典准备就绪');
      }
    } catch (e) {
      print('检查词典状态失败: $e');
    }
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.close, color: Colors.black),
          onPressed: () => Navigator.pop(context),
        ),
        title: const Text(
          '完型填空',
          style: TextStyle(
            color: Colors.black,
            fontSize: 16,
          ),
        ),
        actions: [
          Container(
            margin: const EdgeInsets.all(8),
            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
            decoration: BoxDecoration(
              color: const Color(0xFFFFF3D7),
              borderRadius: BorderRadius.circular(20),
            ),
            child: const Row(
              children: [
                Icon(Icons.card_giftcard, color: Color(0xFFFFB800), size: 16),
                SizedBox(width: 4),
                Text(
                  '答题卡',
                  style: TextStyle(
                    color: Color(0xFFFFB800),
                    fontSize: 12,
                  ),
                ),
              ],
            ),
          ),
          const SizedBox(width: 16),
        ],
      ),
      body: Stack(
        children: [
          SingleChildScrollView(
            padding: EdgeInsets.only(
              left: 16,
              right: 16,
              top: 16,
              bottom: _selectedWord != null ? 100 : 16,
            ),
            child: Text.rich(
              TextSpan(
                children: _buildTextSpans(
                  '    Anxiety is a weight that I have always carried. Once, in my first grade, '
                  'I had to read a book to the whole class. With trembling hands, I walked up to the '
                  'front slowly. I hadn\'t made it to the second page when the tears started. '
                  'I tried to continue, but my teacher\'s glare kept me rooted to the seat. '
                  'Since then the front of the classroom became my greatest fear.',
                ),
              ),
              style: const TextStyle(
                fontSize: 16,
                height: 1.8,
                color: Colors.black87,
              ),
            ),
          ),
        ],
      ),
      bottomSheet: _selectedWord != null
          ? Container(
              width: double.infinity,
              decoration: BoxDecoration(
                color: Colors.black87,
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.1),
                    blurRadius: 4,
                    offset: const Offset(0, -2),
                  ),
                ],
              ),
              padding: EdgeInsets.only(
                left: 16,
                right: 16,
                top: 12,
                bottom: MediaQuery.of(context).padding.bottom + 12,
              ),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    _selectedWord!,
                    style: const TextStyle(
                      color: Colors.white,
                      fontWeight: FontWeight.bold,
                      fontSize: 16,
                    ),
                  ),
                  if (_translation != null) ...[
                    const SizedBox(height: 4),
                    Text(
                      _translation!,
                      style: const TextStyle(
                        color: Colors.white,
                        fontSize: 14,
                      ),
                      softWrap: true,
                      maxLines: 3,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ] else
                    const SizedBox(
                      height: 20,
                      width: 20,
                      child: CircularProgressIndicator(
                        strokeWidth: 2,
                        valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                      ),
                    ),
                ],
              ),
            )
          : null,
    );
  }

  List<InlineSpan> _buildTextSpans(String text) {
    final List<InlineSpan> spans = [];
    final words = text.split(' ');

    for (int i = 0; i < words.length; i++) {
      String word = words[i];
      bool isLastWord = i == words.length - 1;
      
      String punctuation = '';
      if (word.contains(RegExp(r'[.,!?]'))) {
        punctuation = word.substring(word.length - 1);
        word = word.substring(0, word.length - 1);
      }

      spans.add(
        WidgetSpan(
          child: GestureDetector(
            onTap: () => _translateWord(word),
            child: Text(
              word + (isLastWord ? punctuation : '$punctuation '),
              style: TextStyle(
                fontSize: 16,
                height: 1.8,
                color: _selectedWord?.toLowerCase() == word.toLowerCase() 
                    ? const Color(0xFF4B6BFB) 
                    : Colors.black87,
              ),
            ),
          ),
        ),
      );
    }

    return spans;
  }

  void _translateWord(String word) async {
    if (!_dictionaryReady) {
      print('词典未就绪，重新初始化...');
      await _checkDictionary();
      if (!_dictionaryReady) {
        print('词典初始化失败');
        return;
      }
    }

    _timer?.cancel();
    setState(() {
      _selectedWord = word;
      _translation = null;
    });

    final wordInfo = await DictionaryService.queryWord(word.toLowerCase());
    if (mounted && wordInfo != null) {
      setState(() {
        _translation = wordInfo['translation'];
      });

      _timer = Timer(const Duration(seconds: 5), () {
        if (mounted) {
          setState(() {
            _selectedWord = null;
            _translation = null;
          });
        }
      });
    }
  }
}
